package com.xucron.hgmonitor
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.Image
import java.awt.SystemTray
import java.awt.TrayIcon

import org.apache.log4j.Level

import com.codahale.logula.Logging

import javax.swing.ImageIcon
import javax.swing.JMenuItem
import javax.swing.JPopupMenu


object HgMonitor extends App with Logging {

  Logging.configure { log =>
    log.registerWithJMX = true

    log.level = Level.INFO
    log.loggers("com.xucron.hgmonitor") = Level.OFF

    log.console.enabled = true
    log.console.threshold = Level.WARN

    log.file.enabled = false
    log.syslog.enabled = false
  }
  
  if(!SystemTray.isSupported()) { 
    System.out.println("System Tray not supported, cannot run HgMonitor.")
    sys.exit()
  }
  
  log.info("Tray supported")
  
  val contextPopup = createContextPopup()
  val trayIcon = new TrayIcon(createImage("hg.png", "HgMonitor"), "HgMonitor", null)
  SystemTray.getSystemTray().add(trayIcon)
  
  trayIcon.addMouseListener(new MouseAdapter(){
    override def mouseReleased(event: MouseEvent) = {
      if(event.isPopupTrigger()) {
        contextPopup.setLocation(event.getX(), event.getY() - 40);
        contextPopup.setInvoker(contextPopup);
        contextPopup.setVisible(true);
      } else {
        // ON click action goes here
        
      }
    }
    
  })
  
  
  
  /**
   * @param path assumed not <code>null</code> or empty.
   * @param desc may be <code>null</code> or empty.
   */
  private def createImage(path: String, desc: String): Image = {
    val imageUrl = HgMonitor.getClass().getResource(path)
    if(imageUrl == null) {
      log.error("Resource not found: " + path)
      return null
    }
    (new ImageIcon(imageUrl, desc)).getImage()
  }
  
  private def createContextPopup(): JPopupMenu = {
    
    val popup = new JPopupMenu()
    val exitMenuItem = new JMenuItem("Exit")
    val refreshMenuItem = new JMenuItem("Refresh")
    val settingsMenuItem = new JMenuItem("Settings")
    settingsMenuItem.setEnabled(false)
    
    exitMenuItem.addActionListener(new ActionListener() {
       override def actionPerformed(event: ActionEvent) = {sys.exit()}
    })
    
    settingsMenuItem.addActionListener(new ActionListener() {
       override def actionPerformed(event: ActionEvent) = {
        // TODO: invoke settings menu
       }
    })
    
    popup.add(refreshMenuItem)
    popup.add(settingsMenuItem)
    popup.add(exitMenuItem)  
    
    popup
    
  }

  
  

}